from django.shortcuts import render, redirect

from worksite import models
from worksite.myfunc import login_wrapper


@login_wrapper
def search_useinfo(request):
    if request.method == "POST":
        ip = request.POST.get("ip").strip()
        if ip:

            host_id_list = models.Host.objects.filter(ip__startswith=ip).values_list("id", flat=True)

            host_obj_list = models.User.objects.filter(host_id__in=list(host_id_list))

            return render(request, "search/search_useinfo.html", {"user": host_obj_list})
        else:
            return redirect("/userinfo.html")
    return redirect("/userinfo.html")

@login_wrapper
def search_baseline(request):
    if request.method == "POST":
        ip = request.POST.get("ip").strip()
        if ip:
            baseline_obj=models.MyworkBaseline.objects.filter(ip__startswith=ip)
            # print(baseline_obj)
            return render(request, "search/search_baseline.html", {"baseline": baseline_obj})
        else:
            return redirect("/baseline.html")
    return redirect("/baseline.html")

@login_wrapper
def search_myworksoftware(request):
    if request.method == "POST":
        ip = request.POST.get("ip").strip()
        print(ip)
        if ip:
            mysoftwork_id_list=models.MyworkSoftware.objects.filter(ip__startswith=ip).values_list("id", flat=True)
            soft=models.MyworkSoftwareAndSoftware.objects.filter(mywork_software_id__in=list(mysoftwork_id_list))
            # print(soft)
            return render(request, "search/search_myworksoftware.html", {"software": soft, })
        else:
            return redirect("/myworksoftware.html")
    return redirect("/myworksoftware.html")



def search_hostinfo(request):
    if request.method == "POST":
        ip = request.POST.get("ip").strip()
        print(ip)
        if ip:
            vendors = models.Host.objects.filter(ip__startswith=ip)
            return render(request, "search/search_hostinfo.html", {"vendors": vendors, })
        else:
            return redirect("/hostinfo.html")
    return redirect("/hostinfo.html")



